package com.itsu.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itsu.dao.ModuleDao;
import com.itsu.domain.Module;
import com.itsu.service.ModuleService;
import com.itsu.utils.MapperUtils;

import java.util.List;

public class ModuleServiceImpl implements ModuleService {

    private ModuleDao mapper;

    @Override
    public void save(Module module) {
        try {
            mapper = MapperUtils.getMapper(ModuleDao.class);
            mapper.save(module);
            MapperUtils.commit();
        } catch (Exception e) {
            MapperUtils.rollback();
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
    }

    @Override
    public void delete(Module module) {
        try {
            mapper = MapperUtils.getMapper(ModuleDao.class);
            mapper.delete(module);
            MapperUtils.commit();
        } catch (Exception e) {
            MapperUtils.rollback();
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
    }

    @Override
    public void update(Module module) {
        try {
            mapper = MapperUtils.getMapper(ModuleDao.class);
            mapper.update(module);
            MapperUtils.commit();
        } catch (Exception e) {
            MapperUtils.rollback();
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
    }

    @Override
    public Module findById(String id) {
        try {
            mapper = MapperUtils.getMapper(ModuleDao.class);
            Module module = mapper.findById(id);
            return module;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
        return null;
    }

    @Override
    public List<Module> findAll() {
        try {
            mapper = MapperUtils.getMapper(ModuleDao.class);
            List<Module> all = mapper.findAll();
            return all;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
        return null;
    }

    @Override
    public PageInfo<Module> findAll(int pageNum, int pageSize) {
        try {
            mapper = MapperUtils.getMapper(ModuleDao.class);
            PageHelper.startPage(pageNum, pageSize);
            List<Module> all = mapper.findAll();
            PageInfo<Module> modulePageInfo = new PageInfo<>(all);
            return modulePageInfo;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
        return null;
    }
}
